<?php
class info
{
	// database
	protected $db;

	// course wrapper
	protected $wr;

	public function __construct()
	{
		$this->db=Zend_Registry::get('database');

		$this->wr=new wrapper('NId|Title|Content|PostTime|Teacher|Private',
			array('NId'=>'/[0-9]+/', 'Title'=>'/.{4,}/'), 'NId');
	}

	// 出错字段
	public function err_field()
	{
		return $this->wr->field;
	}

	function check($d)
	{ 
		return $this->wr->check($d); 
	}

	// 插入一条, 返回成功的id或者－1表失败
	function add($param)
	{
		$field=$this->wr->field_string($param);
		$key=$this->wr->field_string($param, '', ':');
		$value=$this->wr->filter($param);
		$result=$this->db->query("insert into news ($field) 
				values($key)", $value);
		
		if ($result->rowCount()!=1)
			return -1;
		
		$nid=$this->db->lastInsertId();

		return $nid;
	}

	// 更新新闻信息
	function update($param)
	{
		$value=$this->wr->filter($param);
		$result=$this->db->query('update news
			set Title=:Title, 
				Content=:Content,
				PostTime=:PostTime,
				Teacher=:Teacher,
				Private=:Private
			where NId=:NId', $value);
		if ($result->rowCount()!=1)
			return -1;
		return $param['NId'];		
	}

	// 取消息, bool $private
	function fetch($private, $nid=0, $limit=0)
	{
		$where = $lim = '';
		if ($private)
			$where = ' Private=\'Y\' ';
		else
			$where = ' Private=\'N\' ';
		if ($nid>0)
			$where = ' NId='.intval($nid);
		if ($limit>0)
			$lim = ' limit '.intval($limit);

		$result = $this->db->query('select * from news '.
				" where $where order by NId desc $lim");
		return $result->fetchAll(Zend_Db::FETCH_ASSOC);
	}

	// 删除新闻
	function del($nid)
	{
		$nid = intval($nid);
		try {
			$this->db->query('delete from news where NId='.$nid);
			return 1;
		}
		catch (Zend_Exception $e) {
			return 0;
		}
	}

	// 格式化新闻信息
	static function format($data)
	{
		foreach ($data as $key => $inner) {

			$result[$key]=array();
			foreach ($inner as $k => $v) {

				switch ($k) {
				case 'Content':
					$patten=array('/<(script|iframe)/', 
								  '/<\/(script|iframe)/');
					$v = preg_replace($patten, '&lt;\1', $v);
					$result[$key][$k] = $v;
					break;

				case 'PostTime':
					$result[$key][$k] = strftime('%Y-%m-%d', intval($v));
					break;

				default: $result[$key][$k]=$v;
				} // end of switch

			} // end of for $inner
			
		} // end of for $data
		return $result;
	}
	
};
?>
